package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.UserDao;
import com.cn.wanxi.dao.impl.UserImpl;
import com.cn.wanxi.model.PageBean;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;

import java.util.List;

/**
 * 先判断验证码是否正确，如果不正确则提示验证码不正确
 * 否则去判断用户名和密码
 * 比较是否有相应的用户名和密码
 * 如果有，则提示登录成功
 * 如果数据库没有当前数据，则提示用户名 或者密码输入错误，
 * dao  JDBC
 * 最主要是将后台代码的编写
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserImpl();

    @Override
    public String login(UserModel userModel) {
//        判断验证码是否正确
        boolean isCode = userModel.getCode().equals(userModel.getSessionCode());
        if (!isCode) {
            return "error-code";
        } else {
//            判断用户名和密码是否存在,需要查询数据库，必须通过dao层数据是现场
            UserDao userDao = new UserImpl();
            UserModel model = userDao.findByUsernameAndPassword(userModel);
            if (model != null) {
                return "success";
            } else {
                return "error";
            }

        }

    }

    @Override
    public UserModel findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public String save(UserModel userModel) {
        UserModel model = userDao.findByUsername(userModel.getUsername());
        boolean isHave = model != null;
        if (isHave) {
            return "isHave";
        } else {
            return userDao.save(userModel) > 0 ? "success" : "error";
        }

    }

    @Override
    public String update(UserModel userModel) {
        return userDao.update(userModel) > 0 ? "success" : "error";
    }

    @Override
    public String delete(Integer id) {
        return userDao.delete(id) > 0 ? "success" : "error";
    }

    @Override
    public PageBean<UserModel> findAll(UserModel userModel) {
        PageBean<UserModel> bean = new PageBean<>();
        bean.setList(userDao.findAll(userModel));
        bean.setCount(getCount(userModel));
        return bean;
    }


    @Override
    public String updateEnable(UserModel userModel) {
        return userDao.updateEnable(userModel) > 0 ? "success" : "error";
    }

    @Override
    public int getCount(UserModel userModel) {
        return userDao.getCount(userModel);
    }
}
